<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreNewsRequest;
use App\Http\Requests\UpdateNewsRequest;
use App\Http\Resources\ServiceResource;
use App\Models\News;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $per_page = $request->per_page ?? 10;
        $type = $request->type;
        $title = $request->title;
        $sort = json_decode($request->sort, true);

        $resource = News::select('*')
            ->when($type, function ($query) use ($type) {
                return $query->where('type', $type);
            })
            ->when($title, function ($query) use ($title) {
                return $query->where('title', 'like', '%' . $title . '%');
            })
            ->when($sort, function ($query) use ($sort) {
                foreach ($sort as $item) {
                    $val = str_replace('end', '', $item['order']);
                    $query->orderBy($item['field'], $val);
                }
            }, function ($query) {
                return $query->orderBy('orderby', 'desc');
            })
            ->paginate($per_page);
        return new ServiceResource($resource);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreNewsRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreNewsRequest $request)
    {
        return $this->successful(News::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\News  $news
     * @return \Illuminate\Http\Response
     */
    public function show(News $news)
    {
        return $this->successful($news);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateNewsRequest  $request
     * @param  \App\Models\News  $news
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateNewsRequest $request, News $news)
    {
        return $this->successful($news->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\News  $news
     * @return \Illuminate\Http\Response
     */
    public function destroy(News $news)
    {
        $news->delete();
        return $this->successful();
    }

    /**
     * Delete many resources
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->fail(400, 'ids is required');
        }
        News::whereIn('id', $ids)->delete();
        return $this->successful($ids);
    }
}
